<?php
/**
 * Created by PhpStorm.
 * User: dell
 * Date: 2018/4/30
 * Time: 16:17
 */

namespace app\common\model;
use think\Model;
class User extends Model{
//用户注册
public function regUser($data){

    if(isset($data['username'])){
        $find = $this->where('username',$data['username'])->find();
        if($find){
            return show(400,'该用户名已注册');
        }
    }

    if(isset($data['birthday'])){
        $data['birthday'] = strtotime($data['birthday']);
    }
    if(isset($data['password'])){
        $data['password'] = sha1(md5($data['password']));
    }
    if(isset($data['password_confirm'])){
        $data['password_confirm'] = sha1(md5($data['password_confirm']));
    }
    $data['create_time'] = time();
    $res = $this->validate('Reg')->allowField(true)->save($data);

    if(!$res){
        return show(400,$this->getError());
    }
    return show(200,'注册成功');
}
    public function login($param){
        error_reporting(0);
        $username = isset($param['username'])?trim($param['username']):null;
        $password = isset($param['password'])?trim($param['password']):null;
        if(empty($username)) return show(400,'用户名不能为空');
        if(empty($password)) return show(400,'密码不能为空');
        $res = $this->where('username',$username)->find();
        $id = $res['id'];
        if(!$res){
            return show(400,'用户名或密码错误');
        }
        if($res['password'] !== sha1(md5($password))){
            return show(400,'用户名或密码错误');
        }
        //生成登录Token
        $data['expire_time'] = strtotime('+6 month');
        $data['token'] = sha1(time()).uniqid();
        $result = $this->where('id',$id)->update($data);
        if(!$result){
            return show(400,'登录失败');
        }
        return show(200,登录成功,['id'=>$id,'token'=>$data['token']]);
    }
}